package com.runtu.domain.trade.service.settlement.filter;

import com.runtu.domain.trade.adapter.repository.ITradeRepository;
import com.runtu.domain.trade.model.entity.MarketPayOrderEntity;
import com.runtu.domain.trade.model.entity.TradeSettlementRuleCommandEntity;
import com.runtu.domain.trade.model.entity.TradeSettlementRuleFilterBackEntity;
import com.runtu.domain.trade.service.settlement.factory.TradeSettlementRuleFilterFactory;
import com.runtu.types.design.framework.link.model2.handler.ILogicHandler;
import com.runtu.types.enums.ResponseCode;
import com.runtu.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @ClassName OutTradeNoRuleFilter
 * @Description 外部交易单号过滤；判断外部交易单号是否为退单
 * @date 2025/8/19 23:30
 * @Version 1.0
 */
@Slf4j
@Service
public class OutTradeNoRuleFilter implements ILogicHandler<TradeSettlementRuleCommandEntity, TradeSettlementRuleFilterFactory.DynamicContext, TradeSettlementRuleFilterBackEntity> {

    @Resource
    private ITradeRepository tradeRepository;

    @Override
    public TradeSettlementRuleFilterBackEntity apply(TradeSettlementRuleCommandEntity requestParameter, TradeSettlementRuleFilterFactory.DynamicContext dynamicContext) throws Exception {
        log.info("结算规则过滤-外部单号校验{} outTradeNo:{}", requestParameter.getUserId(), requestParameter.getOutTradeNo());

        //1、查询拼团信息 根据用户id和外部单号查询 MarketPayOrderEntity
        MarketPayOrderEntity marketPayOrderEntity = tradeRepository.queryMarketPayOrderByOutTradeNo(requestParameter.getUserId(), requestParameter.getOutTradeNo());

        //2、如果查不到对应的 直接返回异常码
        if(null == marketPayOrderEntity){
            log.info("不存在的外部交易单号或用户已退单，不需要做支付订单结算:{} outTradeNo:{}", requestParameter.getUserId(), requestParameter.getOutTradeNo());
            throw new AppException(ResponseCode.E0104);
        }

        dynamicContext.setMarketPayOrderEntity(marketPayOrderEntity);

        return next(requestParameter,dynamicContext);

    }
}
